<template>
    <ElTable :data="tableData" class="my-table">
        <ElTableColumn label="角色ID" width="180" prop="id"></ElTableColumn>
        <ElTableColumn label="名称" width="160" prop="name"></ElTableColumn>
        <ElTableColumn label="备注" width="320" prop="remark"></ElTableColumn>
        <ElTableColumn label="角色权限" prop="permissionList">
            <template #default="{ row }">
                {{ getPermissionStr(row?.permissionList) }}
            </template>
        </ElTableColumn>
        <!-- <ElTableColumn label="注册时间" prop="createTime" width="170"></ElTableColumn> -->
        <ElTableColumn label="操作" width="160">
            <template #default="{ row }">
                <ElButton type="danger" link @click="deleteRow(row.id)">删除</ElButton>
                <ElButton type="primary" link @click="editRow(row)">编辑</ElButton>
            </template>
        </ElTableColumn>
    </ElTable>
    <RoleDialog ref="roleEditDialog" @complete="editComplete"></RoleDialog>
</template>

<script setup lang="ts">
import { ElMessageBox, ElMessage } from 'element-plus';
import RoleDialog from './RoleDialog.vue';

interface Params {
    searchKey: string;
    current: number;
    size: number;
}

const tableData = ref<any[]>([]);

const params = ref<Params>({
    searchKey: '',
    current: 1,
    size: 10,
});

const getPermissionStr = (permissionList: any[]): string => {
    let str = '';
    if (Array.isArray(permissionList)) {
        str = permissionList.map((item) => item?.title || '').join(' | ');
    }
    return str;
};

const getData = async (data?: Partial<Params>): Promise<number> => {
    if (data) {
        params.value = { ...params.value, ...data };
    }
    const res = await MyService.account.getRoleList(params.value);
    if (res.code === 200) {
        tableData.value = res.data.records;
        return res.data.total;
    } else {
        return 0;
    }
};

const deleteRow = async (roleId: string) => {
    try {
        await ElMessageBox.confirm('是否确认删除改角色？', '操作提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        });
        const res = await MyService.account.deleteRole([roleId]);
        if (res.code === 200) {
            getData({ current: 1 });
        } else {
            ElMessage.error({ message: res.msg || '角色删除失败' });
        }
    } catch (error) {}
};

const roleEditDialog = ref();

const editRow = async (row: any) => {
    roleEditDialog.value?.open({
        id: row.id,
        name: row.name,
        remark: row.remark,
        permissionList: row.permissionList.map((item: any) => item.id),
    });
};

const editComplete = () => {
    getData({ current: 1 });
};

defineExpose({
    refresh: getData,
});
</script>

<style scoped>
.img-avatar {
    height: 32px;
    width: 32px;
    border-radius: 16px;
    object-fit: contain;
}
</style>
